/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.action.account;

import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import apus.action.Action;
import apus.action.ActionResult;
import apus.entity.*;
import apus.exception.EntityNotFoundException;
import apus.persistence.*;
import apus.services.ServiceLocator;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

/**
 *
 * @author Admin
 */
public class AccountSaveAction implements Action {

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException ex) {
        }

        // if Save button have been pressed
        if (request.getParameter("saveButton") != null) {
            int id = Integer.parseInt(request.getParameter("id"));
            
            String startDate = request.getParameter("startDate");
            String endDate = request.getParameter("endDate");
            if ((startDate != null) && (endDate != null)) {
                DateFormat df = DateFormat.getDateInstance();
                Date start;
                Date end;
                try {
                    start = df.parse(startDate);
                    end = df.parse(endDate);
                } catch (ParseException e) {
                    List<Account> accountList = ServiceLocator.getService(AccountDAO.class).findAll();
                    request.setAttribute("accountList", accountList);
                    request.getSession().setAttribute("fail", "Account data was not saved");
                    return ActionResult.redirect("account.list");                   
                }
                Account account = (id == 0) ? new RealAccount() : ServiceLocator.getService(AccountDAO.class).read(id);

                if (request.getParameter("sub_type") != null) {
                    int sub_id = Integer.parseInt(request.getParameter("sub_id"));
                    Subscriber sub;
                    SubscriberDAO dao = (Integer.parseInt(request.getParameter("sub_type")) == 0)
                            ? ServiceLocator.getService(PersonDAO.class)
                            : ServiceLocator.getService(OrganizationDAO.class);
                    sub = (Subscriber) dao.read(sub_id);
                    account.setSubscriber(sub);
                }
                
                PeriodDAO periodDAO = ServiceLocator.getService(PeriodDAO.class);
                try {
                    periodDAO.readByStartAndEndDates(start, end);
                } catch (EntityNotFoundException e) {
                    periodDAO.create(new RealPeriod(start, end));
                }
                Period period = periodDAO.readByStartAndEndDates(start, end);
                account.setPeriod(period);
                account.calculate();

                AccountDAO accountDAO = ServiceLocator.getService(AccountDAO.class);
                if (id != 0) {
                    accountDAO.update(account); // update account
                    request.getSession().setAttribute("win", "Account was successfully updated");
                } else {
                    accountDAO.create(account); // create account
                    request.getSession().setAttribute("win", "Account was successfully created");
                }
            }
        }
        List<Account> accountList = ServiceLocator.getService(AccountDAO.class).findAll();
        request.setAttribute("accountList", accountList);
        return ActionResult.redirect("account.list");
    }

    @Override
    public String getName() {
        return "account.save";
    }
}
